package cn.fl.project.prjfile.controller;

import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.vo.CapPayMaterialVo;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.prjfile.condition.PrjFilesRecQueryCondition;
import cn.fl.prjfile.constant.PrjFilesRecConstant;
import cn.fl.prjfile.dto.PrjFilesRecDTO;
import cn.fl.project.prjfile.service.IPrjFilesRecService;
import cn.fl.project.prjfile.transform.PrjFilesRecVOTransform;
import cn.fl.project.prjfile.vo.PrjFilesRecVO;
import cn.fl.system.constant.SysLogConstant;
import fl.flow.facade.flow.constant.SysFlowManageConstant;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: 项目补充资料控制层
 */
@Controller
@RequestMapping("/project/prjfile/prjFileRec")
public class PrjFilesRecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PrjFilesRecController.class);

	/**
	 *  服务层BEAN
	 */
	@Autowired
	private IPrjFilesRecService prjFilesRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjfile/PrjFilesRecList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjFilesRecQueryCondition qc = new PrjFilesRecQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		String contractNo = request.getParameter("contractNo");
		if (StringUtils.isNotEmpty(contractNo)) {
			qc.setContractNo(contractNo);
		}
		String paySchNo = request.getParameter("paySchNo");
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		
		//添加权限控制使用-JL-20190822
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.prjFilesRecService.searchListPage(page);
		List<PrjFilesRecVO> list =PrjFilesRecVOTransform.toVOList((List<PrjFilesRecDTO>) pager.getResultList());
		ListPageVO<PrjFilesRecVO> listPage = new ListPageVO<PrjFilesRecVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjFilesRecService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjFilesRecVO vo = this.prjFilesRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		String fileParams=request.getParameter("fileParams");
		String prjId=request.getParameter("prjId");
		String cstId=request.getParameter("cstId");
		String prjPrdDtlId=request.getParameter("prjPrdDtlId");
		String tabNm=request.getParameter("tabNm");
		
		try {
			//根据pkid查询
			String pkId=prjPrdDtlId;
			if ("PRJ_PRD_DTL".equals(tabNm)) {
				pkId=prjPrdDtlId;
			}else if("PRJ_BSC_INFO".equals(tabNm)) {
				pkId=prjId;
			}
			PrjFilesRecQueryCondition condition=new PrjFilesRecQueryCondition();
			condition.setPkId(pkId);
			List<PrjFilesRecVO> listold=this.prjFilesRecService.searchList(condition);
			//赋值添加记录
			List<JSONObject> list=JSONObject.parseArray(fileParams,JSONObject.class);			
			List<PrjFilesRecVO> list2=new ArrayList<PrjFilesRecVO>();			
			for (JSONObject obj :list) {
				PrjFilesRecVO vo=new PrjFilesRecVO();
				vo.setSysCd(obj.getString("sysCd"));
				if (vo.getSysCd()==null) {
					vo.setSysCd(CapitalConstant.SYSCD);
				}
				vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				vo.setOrgCd(obj.getString("orgCd"));
				vo.setCfgCd(obj.getString("cfgCd"));
				vo.setCfgDtlCd(obj.getString("cfgDtlCd"));
				vo.setTabNm(tabNm);
				vo.setPrjId(Long.valueOf(prjId));
				vo.setPayPrdDtlId(Long.valueOf(prjPrdDtlId));
				vo.setCstId(Long.valueOf(cstId));
				vo.setStsCd(PrjFilesRecConstant.PRJ_FILES_REC_STS_DAITIJIAO);
				vo.setPkId(pkId);
				list2.add(vo);
				for (PrjFilesRecVO rvo: listold) {
					//如果通过了，改成待提交
					if (PrjFilesRecConstant.PRJ_FILES_REC_STS_TONGGUO.equals(rvo.getStsCd()) 
							&&rvo.getCfgCd().equals(vo.getCfgCd())
							&&rvo.getCfgDtlCd().equals(vo.getCfgDtlCd())) {
						this.prjFilesRecService.modifyAudStsCdById(rvo.getId(), PrjFilesRecConstant.PRJ_FILES_REC_STS_DAITIJIAO);
						list2.remove(vo);
					//如果已经存在，不重新加记录
					}else if (rvo.getCfgCd().equals(vo.getCfgCd())
							&&rvo.getCfgDtlCd().equals(vo.getCfgDtlCd())) {
						list2.remove(vo);
					}
				}
			}
			
			//TODO ADD PARAM
			this.prjFilesRecService.addList(list2);
			
			BaseLogUtils.info(logger, "add", "新增数据.[id=] DATA:" + JSONObject.toJSONString(fileParams), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(fileParams) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(fileParams) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object modify(PrjFilesRecVO entity,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjFilesRecService.update(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String prjPrdDtlId = request.getParameter("id");
		String ctrlKey = request.getParameter("ctrlKey");
		ModelAndView view = new ModelAndView("project/prjfile/PrjFilesRecAdd");
		view.addObject("prjPrdDtlId", prjPrdDtlId);
		
		view.addObject("ctrlKey", ctrlKey);
		Pager page=new Pager();
		PrjFilesRecQueryCondition qc=new PrjFilesRecQueryCondition();
		qc.setPayPrdDtlId(Long.parseLong(prjPrdDtlId));
		page.setCondition(qc);
		//TODO SOMETHING
		Pager pager = this.prjFilesRecService.searchListPage(page);
		List<PrjFilesRecDTO> list = (List<PrjFilesRecDTO>) pager.getResultList();
		if (list!=null) {
			view.addObject("prjFilesRecVO", list.get(0));
			view.addObject("prjId", list.get(0).getPrjId());
		}
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[prjPrdDtlId="+prjPrdDtlId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
    /**
     * 初始化上传资料列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initMateList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initMateList(HttpServletRequest request, HttpServletResponse response) {
        
        //产品明细ID
        String prjPrdDtlId = request.getParameter("prjPrdDtlId");
       
        //项目ID
        String prjId = request.getParameter("prjId");
       
        //设置查询条件？
        PrjFilesRecQueryCondition qc = new PrjFilesRecQueryCondition();
		
		if (StringUtils.isNotEmpty(prjPrdDtlId)) {
			qc.setPayPrdDtlId(Long.parseLong(prjPrdDtlId));
		}
		if (StringUtils.isNotEmpty(prjId)) {
			qc.setPrjId(Long.parseLong(prjId));
		}
		String tabNm = request.getParameter("tabNm");
		String pkId=prjPrdDtlId;
		if ("PRJ_PRD_DTL".equals(tabNm)) {
			pkId=prjPrdDtlId;
		}else if("PRJ_BSC_INFO".equals(tabNm)) {
			pkId=prjId;
		}
		qc.setPkId(pkId);
		qc.setTabNm(tabNm);
        BaseLogUtils.info(logger, "initMateList", "初始化上传资料列表.DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
        List<CapPayMaterialVo> list = this.prjFilesRecService.searchMateList(qc);
        if (CollectionUtils.isNotEmpty(list)) {
            return new ListPageVO<CapPayMaterialVo>(list, list.size());
        }
        return null;
    }
    /**
	 * 发起流程
	 */
	@RequestMapping(value = "/saveFlow.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object saveFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String paySchNo = request.getParameter("paySchNo");
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "saveFlow", "发起流程,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			//发起流程
			Map flwomap=new HashMap();
			flwomap.put("id", id);
			flwomap.put("paySchNo", paySchNo);
			String keyword="";
			keyword=paySchNo; 
			flwomap.put("keyword",keyword.toString());
			BaseLogUtils.info(logger, "add","关键字--"+keyword.toString());
			DataResultDTO dataResultDTO=this.prjFilesRecService.addFlowStart(flwomap);
			if (!dataResultDTO.getCode().equals(
					BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(dataResultDTO.getInfo());
			}else if (null != dataResultDTO && null != dataResultDTO.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO
						.getData();
				if (StringUtils
						.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:"
							+ flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功:"+flowStartedDTO.getProcInstanceNo());
				}
				//更改状态
				Long prjId=null;
				//查找设备资料
				PrjFilesRecQueryCondition condition = new PrjFilesRecQueryCondition();
				condition.setPayPrdDtlId(Long.parseLong(id));
				List<PrjFilesRecVO> list =this.prjFilesRecService.searchList(condition);
				List<Long> idList=new ArrayList<Long>() ;
				for (PrjFilesRecVO vo: list) {
					prjId=vo.getPrjId();
					idList.add(vo.getId());
				}
				//查找项目资料
				PrjFilesRecQueryCondition condition2 = new PrjFilesRecQueryCondition();
				condition2.setPkId(prjId.toString());
				List<PrjFilesRecVO> list2 =this.prjFilesRecService.searchList(condition2);
				for (PrjFilesRecVO vo: list2) {
					idList.add(vo.getId());
				}
				//更改状态
				this.prjFilesRecService.modifyAudStsCdByIdList(idList, PrjFilesRecConstant.PRJ_FILES_REC_STS_SHENHEZHONG);
			}
			BaseLogUtils.info(logger, "saveFlow", "发起流程成功.[id="+id+"] DATA:" + JSONObject.toJSONString(dataResultDTO), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "saveFlow", "发起流程失败.[id="+id+"] DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "saveFlow", "发起流程失败.[id="+id+"] DATA:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
  
}

